#include "util.hpp"

int main()
{
    // 1.创建key，并获取shm,返回shmid
    key_t key = CreateKey();
    int shmid = shmget(key, MEM_SIZE, IPC_CREAT | 0666);
    if (shmid < 0)
    {
        cerr << "shmget:" << strerror(errno) << endl;
        return 2;
    }

    // 2.关联共享内存
    char *shm = (char *)shmat(shmid, nullptr, 0);
    if (shm == (void *)-1)
    {
        cerr << "shmat error" << endl;
        return 3;
    }

    // 3.使用共享内存
    while (1)
    {
        printf("Please Enter#");
        fflush(stdout);
        ssize_t s = read(0, shm, MEM_SIZE); // 从键盘信息写入共享内存
        if (s > 0)
            shm[s - 1] = '\0';
        char *str = shm;
        if (strncasecmp(str, "QUIT", 4) == 0) // 用户控制退出，忽略大小写,需要使用strncasecmp
        {
            cout << "client quit!" << endl;
            break;
        }
    }

    // 4.去关联共享内存
    shmdt(shm);
    cout << "detach shm success!" << endl;

    return 0;
}